import React,{useState,useEffect} from 'react';
import { ipcRenderer } from 'electron';
import './peer-puppet'
const Gui = () =>{
  const [remoteCode,setRometeCode] = useState('')//输入的控制码
  const [localCode,setLocalCode] = useState('')//自己的控制码
  const [controlText,setControlText] = useState('')//连接状态
  const login = async()=>{
    //登陆函数
    const code =await ipcRenderer.invoke('login')
    setLocalCode(code)
  }
  useEffect(()=>{
    login()
    ipcRenderer.on('control-state-change',handleControlState)//监听事件
    //卸载组件
    return ()=>{
      ipcRenderer.removeListener('control-state-change',handleControlState)
    }
  },[])
  const startControl=(remoteCode)=>{
    //开始控制
    ipcRenderer.send('control',remoteCode)
  }
  const handleControlState=(e,name,type)=>{
    //处理事件
    let text=''
    if(type===1){
      text = `正在远程控制${name}`
    }else if(type===2){
      text = `正在被${name}远程控制`
    }
    setControlText(text)
  }
  return (
    <div className='App'>
      {
        controlText ===''?
        <><div>你的控制码{localCode}</div><input type='text' onChange={e=>setRometeCode(e.target.value)}/><button onClick={()=>startControl(remoteCode)}>确认</button></>
        :<div>{controlText}</div>
      }
    </div>
  )
};

export default Gui
